package com.example.port.Controller;

import com.example.port.dto.ApiResponse;
import com.example.port.entity.PortArea;
import com.example.port.service.PortAreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/port-areas")
public class PortAreaController {
    
    private final PortAreaService portAreaService;
    
    @Autowired
    public PortAreaController(PortAreaService portAreaService) {
        this.portAreaService = portAreaService;
    }
    
    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public ApiResponse<Integer> createPortArea(@RequestBody PortArea portArea) {
        int result = portAreaService.insertPortArea(portArea);
        if (result > 0) {
            return ApiResponse.success(result);
        }
        return ApiResponse.error(500, "创建港口区域失败");
    }
    
    @GetMapping
    public ApiResponse<List<PortArea>> getAllPortAreas() {
        List<PortArea> portAreas = portAreaService.getAllPortAreas();
        return ApiResponse.success(portAreas);
    }
    
    @GetMapping("/{id}")
    public ApiResponse<PortArea> getPortAreaById(@PathVariable Integer id) {
        PortArea portArea = portAreaService.getPortAreaById(id);
        if (portArea != null) {
            return ApiResponse.success(portArea);
        }
        return ApiResponse.error(404, "未找到指定的港口区域");
    }
    
    @DeleteMapping("/{id}")
    public ApiResponse<Integer> deletePortArea(@PathVariable Integer id) {
        int result = portAreaService.deletePortArea(id);
        if (result > 0) {
            return ApiResponse.success(result);
        }
        return ApiResponse.error(500, "删除港口区域失败");
    }
    
    @PutMapping("/{id}")
    public ApiResponse<Integer> updatePortArea(@PathVariable Integer id, @RequestBody PortArea portArea) {
        portArea.setAreaId(id);
        int result = portAreaService.updatePortArea(portArea);
        if (result > 0) {
            return ApiResponse.success(result);
        }
        return ApiResponse.error(500, "更新港口区域失败");
    }
    
    @PutMapping("/{id}/usage")
    public ApiResponse<Integer> updatePortAreaUsage(@PathVariable Integer id, @RequestParam("usage") Double usage) {
        int result = portAreaService.updatePortAreaUsage(id, usage);
        if (result > 0) {
            return ApiResponse.success(result);
        }
        return ApiResponse.error(500, "更新港口区域使用量失败");
    }
} 
